<?php
/**
 * FastApp.
 * 8/21/25
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Ai\Api;

use App\Ai\Model\AiAccountChat;
use App\Fastapp\Api\Controller\ApiController;
use App\Fastapp\Aspect\ApiAuth;
use GuzzleHttp\Client;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;
use TheoGibbons\ChromaPHP\ChromaDBClient;

#[Controller(prefix: "api/ai/chat")]
class ChatController extends ApiController
{
    #[PostMapping("query"), ApiAuth]
    public function query(): ResponseInterface
    {
        $param = $this->validate(['query' => 'required|string', 'ai_chat_id' => 'required|integer']);
        $tenantName = env('CHROMADB_TENANT');
        $databaseName = env('CHROMADB_DATABASE');
        $collection_db = env('CHROMADB_DB');
        $chroma = ChromaDBClient::connect([
            'host' => env('CHROMADB_HOST'),
            'port' => env('CHROMADB_PORT'),
//            'authToken'=>env(),
        ]);
        $query = $param['query'];

        $client = new Client();
        $response = $client->post(env('SERVER_AI_EMBED') . '/embed', [
            'json' => ['text' => $query]
        ]);
        $data = json_decode($response->getBody()->getContents(), true);
        $res = $chroma->queryCollection($tenantName, $databaseName, $collection_db, [
            'query_embeddings' => $data['embeddings'],
            'n_results' => 5,
        ]);
        $uid = get_uid();
        $chat_id = get_user_cache('ai_chat_id');
        $list = AiAccountChat::query()->where(['user_id' => $uid, 'chat_id' => $chat_id])->orderByDesc('id')->limit(6)->get()->reverse();
        $message = [];
        if ($list->isEmpty()) $message[] = ['role' => 'system', 'content' => '你是一位知识助手，请根据用户的问题和下列片段生成准确的回答。'];
        foreach ($list as $item) $message[] = ['role' => $item['role'], 'content' => $item['content']];
        $query_data['role'] = 'user';
        if ($res['documents'][0]) {
            $response = $client->post(env('SERVER_AI_EMBED') . '/rerank', [
                'json' => ['query' => $query, 'chunks' => $res['documents'][0]]
            ]);
            $data = json_decode($response->getBody()->getContents(), true);
            $query_data['content'] = '用户问题: ' . $query . '
相关片段:
' . implode('\n', $data) . '
请基于上述内容作答，不要编造信息。';
        } else {
            $query_data['content'] = '用户问题: ' . $query;
        }
        $message[] = $query_data;
        $start = microtime(true);
        $client = \OpenAI::factory()
//            ->withApiKey('sk-06983df4533b41e7a4decb49e20f10f7')
//            ->withBaseUri('https://api.deepseek.com')
            ->withBaseUri('http://0.0.0.0:8100/v1')
            ->withHttpClient(new Client(['timeout' => 180]))
            ->make();

        $response = $client->chat()->create([
            'model' => 'deepseek-chat',
            'messages' => $message,
        ]);
        /*$response = $client->chat()->create([
            'model' => 'phi',
            'messages' => [
                [
                    'role' => 'user', 'content' => '你是一位知识助手，请根据用户的问题和下列片段生成准确的回答。

用户问题: 哆啦A梦使用的3个秘密道具分别是什么？

相关片段:
三件秘密道具分别是：可以临时赋予超级战力的“复制斗篷”，能暂停时神与时光屋便携版”。大雄被推进精神屋内，在其中接受密集的训练，虽软弱，想放弃、想逃跑，但当他想起静香、父母，还有哆啦A梦那坚定的一新，眼神中多了一份成熟与自信。\n战后，未来世界开始恢复，植物“你是我见过最特别的战士。”哆啦A梦也为大雄感到骄傲，说他终于真正，看着远方重新明亮的地平线，心中感受到从未有过的安宁。随后，哆平静。\n最终战在黑暗赛亚人的空中要塞前爆发，特兰克斯率先出击，方向制造混乱，尽量压制敌人的时空能力。但黑暗赛亚人太过强大，仅之际，大雄披上复制斗篷、冲破恐惧从高空跃下。他的拳头燃烧着金色光焰，目标直指敌人心脏。

请基于上述内容作答，不要编造信息。',],
            ],
        ]);
        print_r($response->choices);
        return $this->success();*/
        var_dump(microtime(true) - $start);
        AiAccountChat::query()->insert([
            [
                'user_id' => $uid,
                'role' => 'user',
                'chat_id' => $chat_id,
                'content' => $query
            ],
            [
                'user_id' => $uid,
                'role' => 'assistant',
                'chat_id' => $chat_id,
                'content' => ($response->choices[0])->message->content
            ]
        ]);

        return $this->success(['role' => 'assistant', 'content' => ($response->choices[0])->message->content]);
    }

    #[PostMapping("setChatId"), ApiAuth]
    public function setChatId(): ResponseInterface
    {
        $param = $this->validate(['ai_chat_id' => 'required|integer']);
        set_user_cache(['ai_chat_id' => $param['ai_chat_id']]);
        return $this->success();
    }

    #[GetMapping("createChat"), ApiAuth]
    public function createChat(): ResponseInterface
    {
        $ai_chat_id = redis()->hIncrBy('gene', 'ai_chat', 1);
        set_user_cache(['ai_chat_id' => $ai_chat_id]);
        return $this->success(['ai_chat_id' => $ai_chat_id]);
    }

    #[GetMapping("delChat"), ApiAuth]
    public function delChat(): ResponseInterface
    {
        $param = $this->validate(['ai_chat_ids' => 'required|array']);
        AiAccountChat::query()->where(['user_id' => get_uid()])->whereIn('chat_id', $param['ai_chat_ids'])->delete();
        return $this->success();
    }

    #[GetMapping("getChatList"), ApiAuth]
    public function getChatList(): ResponseInterface
    {
        $list = AiAccountChat::query()->where(['user_id' => get_uid()])->groupBy('chat_id')->get();
        return $this->success(['list' => $list->reverse()]);
    }


    #[GetMapping("getChatDetail"), ApiAuth]
    public function getChatDetail(): ResponseInterface
    {
        $param = $this->validate(['ai_chat_id' => 'required|integer']);
        $list = AiAccountChat::query()->where(['user_id' => get_uid(), 'chat_id' => $param['ai_chat_id']])->get();
        return $this->success(['list' => $list]);
    }

}